/*
* @Author: willes
* @Date:   2015-12-11 10:27:53
* @Last Modified by:   Administrator
* @Last Modified time: 2015-12-15 13:34:13
*/
window.onload = function(){
	var oparent = document.getElementById('main');
	var apin = getClassObj(oparent,'pin');
	// var opin = document.createElement('div');
	// opin.class="pink";
	// var obox = document.createElement('div');
	// obox.className = 'box';
	// var oimg = document.createElement('img');
	// obox.appendChild(oimg);
	// opin.appendChild(obox);
	// document.getElementById('main').appendChild(opin);
	waterfull('main','pin');
	window.onscroll=function(){
		var ajaxStatus = true;
		if(checkScroll() && ajaxStatus){
			$.ajax({
			url: 'data.php',
			type: 'get',
			dataType: 'json',
			beforeSend:function(){
			},
			success:function(data){
				console.log(data);
				for(var i in data){
					var objurl = data[i].big;
					var opin = document.createElement('div');
					opin.className="pin";
					var obox = document.createElement('div');
					obox.className = 'box';
					var oimg = document.createElement('img');
					oimg.src=objurl;
					obox.appendChild(oimg);
					opin.appendChild(obox);
					document.getElementById('main').appendChild(opin);
				}
				waterfull('main','pin');
				ajaxStatus = false;
			},
			complete:function(){
				ajaxStatus = true;
			}
		})
		}
	}

	function waterfull(id,className){
	var oparent = document.getElementById(id);
	var apin = getClassObj(oparent,className);
	var pinw = apin[0].offsetWidth;
	var oclientw = document.documentElement.clientWidth;
	var inums = Math.floor(oclientw/pinw);
	oparent.style.cssText = 'width:'+inums*pinw+'px';
	var arrayheight = [];
	for(var i = 0;i < apin.length;i++){
		if(i<inums){
			arrayheight[i] = apin[i].offsetHeight;
		}else{
			//获取数组中最小的高度
		var minHeight = Math.min.apply([],arrayheight);
		var minKey = getMinKey(arrayheight,minHeight);
		apin[i].style.position="absolute";
		apin[i].style.top = minHeight+'px';
		apin[i].style.left = apin[minKey].offsetLeft+'px';
		arrayheight[minKey]+=apin[i].offsetHeight;
		}
	}

	}

// 获取样式
function getClassObj(oparent,className){
	var obj = oparent.getElementsByTagName('*');
	var result=[];
	for(var i =0 ;i<obj.length;i++){
		if(obj[i].className == className){
			result.push(obj[i]);
		}
	}
	return result;
}
//获取数组中最小的高度对应的索引
function getMinKey(arr,minHeight){
	for(var key in arr){
		if(arr[key] == minHeight){
			return key;
		}
	}
}
//检查是否滑到页面底部
function checkScroll(){
	var oparent = document.getElementById('main');
	var apin = getClassObj(oparent,'pin');
	var lastH = apin[apin.length - 1].offsetTop + Math.floor(apin[apin.length - 1].offsetHeight/2);
	var scrollH = document.documentElement.clientHeight+(document.documentElement.scrollTop || document.body.scrollTop);
	return scrollH>lastH ? true : false;
}
}
